package com.idbk.chargestation.activity.charge;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.idbk.chargestation.AppContext;
import com.idbk.chargestation.R;
import com.idbk.chargestation.activity.assist.ActivityHelp;
import com.idbk.chargestation.api.APIForCharge;
import com.idbk.chargestation.base.BaseActivity;
import com.idbk.chargestation.bean.JsonGunChargeStatus;
import com.idbk.chargestation.bean.JsonPointPile;
import com.idbk.chargestation.bean.JsonQrScan;
import com.idbk.chargestation.net.EHttpResponse;
import com.idbk.chargestation.util.GlobalResult;
import com.idbk.chargestation.util.GsonUtils;
import com.idbk.chargestation.view.EToolbar2;

/**
 * 双枪界面
 * @author zhx
 *
 */
public class ActivityDoubleGun extends BaseActivity implements OnClickListener{

	/**
	 * 数据刷新时间
	 */
	public final static int DOUBLE_GUN_REFRESH = 5000;
	private TextView mPoint, mSn, mStyle, mCost, mPerformance;
	private TextView mTip, mConnect, mNext;
	private TextView mGunInfor, mGunA, mGunB;
	private JsonQrScan mQrScanData;
	private LinearLayout mLinearTip;
	private RelativeLayout mRelateGunA, mRelateGunB;
	private ImageView mCheckA, mCheckB;
	private boolean isGunAOccupy = false;
	private boolean isGunBOccupy = false;
	private boolean isChoose = false;
	private SpannableString spanATip, spanBTip;
	private Handler handler;
	private String mPileSn, mTextTip;

	/**
	 * 默认选择的枪号
	 */
	private int mGunNum = JsonPointPile.GUN_A;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_double_gun);

		setupView();

		setupData();
	}

	private void setupView() {
		mToolbar2 = (EToolbar2) findViewById(R.id.tj_toolbar2);
		mToolbar2.setTitle(getToolBarTitle());
		mToolbar2.getBackView().setOnClickListener(this);

		mPoint = (TextView) findViewById(R.id.point);
		mSn = (TextView) findViewById(R.id.sn);
		mStyle = (TextView) findViewById(R.id.style);
		mCost = (TextView) findViewById(R.id.cost);
		mPerformance = (TextView) findViewById(R.id.performance);
		mTip = (TextView) findViewById(R.id.activity_tip);
		mGunInfor = (TextView) findViewById(R.id.gun_inf);
		mGunA = (TextView) findViewById(R.id.gunA);
		mGunB = (TextView) findViewById(R.id.gunB);

		mLinearTip = (LinearLayout) findViewById(R.id.layout_double);
		mRelateGunA = (RelativeLayout) findViewById(R.id.layout_gunA);
		mRelateGunB = (RelativeLayout) findViewById(R.id.layout_gunB);
		if (mRelateGunA != null && mRelateGunB != null) {
			mRelateGunA.setOnClickListener(this);
			mRelateGunB.setOnClickListener(this);
			// 初始化不给点击，获取枪的实时状态后再运行点击
			mRelateGunA.setClickable(false);
			mRelateGunB.setClickable(false);
		}

		mCheckA = (ImageView) findViewById(R.id.checkA);
		mCheckB = (ImageView) findViewById(R.id.checkB);

		mConnect = (TextView) findViewById(R.id.activity_connect);
		mNext = (TextView) findViewById(R.id.textview_next);
		if (mConnect != null && mNext != null) {
			mConnect.setOnClickListener(this);
			mNext.setOnClickListener(this);
			// 初始化不给点击，获取枪的实时状态后再运行点击
			mNext.setClickable(false);
		}
	}

	private void setupData() {
		mQrScanData = getIntent().getParcelableExtra(JsonQrScan.KEY);
		mPoint.setText(mQrScanData.pointName);
		mSn.setText(mQrScanData.pileSn);
		mStyle.setText(mQrScanData.performance);
		mCost.setText(mQrScanData.getPriceTypeString());
		mPerformance.setText(mQrScanData.chargeSpeed);

		mPileSn = mQrScanData.pileSn;
		mTextTip = "请将充电枪与车辆充电口正确连接";

		SpannableString spanTip = new SpannableString("该类型电桩自带 2 把充电枪可供使用（枪1、枪2）:");
		spanTip.setSpan(new AbsoluteSizeSpan(12, true), 0, 8, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		spanTip.setSpan(new ForegroundColorSpan(ContextCompat.getColor(this, R.color.tj_text_content_3)),
				0, 8, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
		spanTip.setSpan(new AbsoluteSizeSpan(14, true), 8, 9, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		spanTip.setSpan(new ForegroundColorSpan(ContextCompat.getColor(this, R.color.tj_theme)),
				8, 9, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
		spanTip.setSpan(new AbsoluteSizeSpan(12, true), 9, 26, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		spanTip.setSpan(new ForegroundColorSpan(ContextCompat.getColor(this, R.color.tj_text_content_3)),
				9, 26, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
		mGunInfor.setText(spanTip);

		spanATip = spanGun("车辆与 枪1 连接成功，请点击下一步");
		spanBTip = spanGun("车辆与 枪2 连接成功，请点击下一步");

		if (mQrScanData.gunA == JsonPointPile.STATUS_CHARGING || mQrScanData.gunA == JsonPointPile.STATUS_FINISH) {
			mGunA.setCompoundDrawablesWithIntrinsicBounds(null, null, null,
					ContextCompat.getDrawable(ActivityDoubleGun.this, R.drawable.ico_charging_gun_disabled));
			isGunAOccupy = true;
		}

		if (mQrScanData.gunB == JsonPointPile.STATUS_CHARGING || mQrScanData.gunB == JsonPointPile.STATUS_FINISH) {
			mGunB.setCompoundDrawablesWithIntrinsicBounds(null, null, null,
					ContextCompat.getDrawable(ActivityDoubleGun.this, R.drawable.ico_charging_gun_disabled));
			isGunBOccupy = true;
		}
		handler = new Handler();

	}

	public SpannableString spanGun(String str) {
		SpannableString span = new SpannableString(str);
		span.setSpan(new AbsoluteSizeSpan(12, true), 0, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		span.setSpan(new ForegroundColorSpan(ContextCompat.getColor(this, R.color.tj_text_content_3)), 0, 4, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
		span.setSpan(new AbsoluteSizeSpan(14, true), 4, 6, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		span.setSpan(new ForegroundColorSpan(ContextCompat.getColor(this, R.color.tj_theme)), 4, 6, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
		span.setSpan(new AbsoluteSizeSpan(12, true), 6, 18, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		span.setSpan(new ForegroundColorSpan(ContextCompat.getColor(this, R.color.tj_text_content_3)), 6, 18, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
		return span;
	}
	
	
	@Override
	protected void onStart() {
		if(AppContext.getInstance().isLogin()) {
			handler.post(runnable);
		}
		super.onStart();
	}

	@Override
	protected void onStop() {
		handler.removeCallbacks(runnable);
		super.onStop();
	}

	Runnable runnable = new Runnable() {

		@Override
		public void run() {
			APIForCharge.getChargeGunStatus(mPileSn, new EHttpResponse() {

				@Override
				public void onEResponse(String response) {
					JsonGunChargeStatus result = GsonUtils.toBean(JsonGunChargeStatus.class, response);
					if (result == null) {
						Toast.makeText(ActivityDoubleGun.this, R.string.common_tip_resultnull, Toast.LENGTH_SHORT).show();

					} else if (result.status == GlobalResult.OK.getStatus()) {
						//枪A和枪B都没被占用
						if ((!isGunAOccupy) && (!isGunBOccupy)) {
							if ((result.gunA == JsonPointPile.STATUS_CHARGING || result.gunA == JsonPointPile.STATUS_FINISH || result.gunA == JsonPointPile.STATUS_WAIT)
									&& (result.gunB == JsonPointPile.STATUS_CHARGING || result.gunB == JsonPointPile.STATUS_FINISH || result.gunB == JsonPointPile.STATUS_WAIT)) {
								if (!isChoose) {
									mGunA.setCompoundDrawablesWithIntrinsicBounds(null, null, null,
											ContextCompat.getDrawable(ActivityDoubleGun.this, R.drawable.ico_charging_gun_connected));
									mGunB.setCompoundDrawablesWithIntrinsicBounds(null, null, null,
											ContextCompat.getDrawable(ActivityDoubleGun.this, R.drawable.ico_charging_gun_connected));
									mTip.setVisibility(View.GONE);
									mConnect.setVisibility(View.GONE);
									mLinearTip.setVisibility(View.VISIBLE);
									mCheckA.setVisibility(View.VISIBLE);
									mCheckB.setVisibility(View.VISIBLE);
									mRelateGunA.setClickable(true);
									mRelateGunB.setClickable(true);
									mNext.setBackgroundResource(R.drawable.bg_main_button_sm_black);
									mNext.setClickable(false);
								}
							} else if (result.gunA == JsonPointPile.STATUS_CHARGING
									|| result.gunA == JsonPointPile.STATUS_FINISH
									|| result.gunA == JsonPointPile.STATUS_WAIT) {
								mGunA.setCompoundDrawablesWithIntrinsicBounds(null, null, null,
										ContextCompat.getDrawable(ActivityDoubleGun.this, R.drawable.ico_charging_gun_connected));
								mGunB.setCompoundDrawablesWithIntrinsicBounds(null, null, null,
										ContextCompat.getDrawable(ActivityDoubleGun.this, R.drawable.ico_charging_gun_disconnect));
								mTip.setVisibility(View.VISIBLE);
								mTip.setText(spanATip);
								mConnect.setVisibility(View.GONE);
								mLinearTip.setVisibility(View.GONE);
								mCheckA.setVisibility(View.GONE);
								mCheckB.setVisibility(View.GONE);
								mRelateGunA.setClickable(false);
								mRelateGunB.setClickable(false);
								mNext.setBackgroundResource(R.drawable.bg_main_button_lg_sprite_2);
								mNext.setClickable(true);
								mGunNum = JsonPointPile.GUN_A;
								isChoose = false;

							} else if (result.gunB == JsonPointPile.STATUS_CHARGING
									|| result.gunB == JsonPointPile.STATUS_FINISH
									|| result.gunB == JsonPointPile.STATUS_WAIT) {
								mGunA.setCompoundDrawablesWithIntrinsicBounds(null, null, null,
										ContextCompat.getDrawable(ActivityDoubleGun.this, R.drawable.ico_charging_gun_disconnect));
								mGunB.setCompoundDrawablesWithIntrinsicBounds(null, null, null,
										ContextCompat.getDrawable(ActivityDoubleGun.this, R.drawable.ico_charging_gun_connected));
								mTip.setVisibility(View.VISIBLE);
								mTip.setText(spanBTip);
								mConnect.setVisibility(View.GONE);
								mLinearTip.setVisibility(View.GONE);
								mCheckA.setVisibility(View.GONE);
								mCheckB.setVisibility(View.GONE);
								mRelateGunA.setClickable(false);
								mRelateGunB.setClickable(false);
								mNext.setBackgroundResource(R.drawable.bg_main_button_lg_sprite_2);
								mNext.setClickable(true);
								mGunNum = JsonPointPile.GUN_B;
								isChoose = false;

							} else {
								mGunA.setCompoundDrawablesWithIntrinsicBounds(null, null, null,
										ContextCompat.getDrawable(ActivityDoubleGun.this, R.drawable.ico_charging_gun_disconnect));
								mGunB.setCompoundDrawablesWithIntrinsicBounds(null, null, null,
										ContextCompat.getDrawable(ActivityDoubleGun.this, R.drawable.ico_charging_gun_disconnect));
								mTip.setVisibility(View.VISIBLE);
								mConnect.setVisibility(View.VISIBLE);
								mLinearTip.setVisibility(View.GONE);
								mCheckA.setVisibility(View.GONE);
								mCheckB.setVisibility(View.GONE);
								mRelateGunA.setClickable(false);
								mRelateGunB.setClickable(false);
								mNext.setBackgroundResource(R.drawable.bg_main_button_sm_black);
								mNext.setClickable(false);
								mTip.setText(mTextTip);
								isChoose = false;
							}
							//枪A没被占用，枪B被占用
						} else if (!isGunAOccupy && isGunBOccupy) {
							mCheckA.setVisibility(View.GONE);
							mCheckB.setVisibility(View.GONE);
							mRelateGunA.setClickable(false);
							mRelateGunB.setClickable(false);

							if (result.gunA == JsonPointPile.STATUS_CHARGING
									|| result.gunA == JsonPointPile.STATUS_FINISH
									|| result.gunA == JsonPointPile.STATUS_WAIT) {
								mGunA.setCompoundDrawablesWithIntrinsicBounds(null, null, null,
										ContextCompat.getDrawable(ActivityDoubleGun.this, R.drawable.ico_charging_gun_connected));
								mTip.setVisibility(View.VISIBLE);
								mTip.setText(spanATip);
								mConnect.setVisibility(View.GONE);
								mLinearTip.setVisibility(View.GONE);
								mNext.setBackgroundResource(R.drawable.bg_main_button_lg_sprite_2);
								mNext.setClickable(true);
								mGunNum = JsonPointPile.GUN_A;
								isChoose = false;
							}

							if (result.gunB == JsonPointPile.STATUS_IDLE) {
								mGunB.setCompoundDrawablesWithIntrinsicBounds(null, null, null,
										ContextCompat.getDrawable(ActivityDoubleGun.this, R.drawable.ico_charging_gun_disconnect));
								isGunBOccupy = false;

							} else if (result.gunB == JsonPointPile.STATUS_WAIT) {
								mGunB.setCompoundDrawablesWithIntrinsicBounds(null, null, null,
										ContextCompat.getDrawable(ActivityDoubleGun.this, R.drawable.ico_charging_gun_connected));
								isGunBOccupy = false;

							} else {
								mGunB.setCompoundDrawablesWithIntrinsicBounds(null, null, null,
										ContextCompat.getDrawable(ActivityDoubleGun.this, R.drawable.ico_charging_gun_disabled));
							}
							//枪B没被占用，枪A被占用
						} else if (!isGunBOccupy && isGunAOccupy) {
							mCheckA.setVisibility(View.GONE);
							mCheckB.setVisibility(View.GONE);
							mRelateGunA.setClickable(false);
							mRelateGunB.setClickable(false);

							if (result.gunB == JsonPointPile.STATUS_CHARGING
									|| result.gunB == JsonPointPile.STATUS_FINISH
									|| result.gunB == JsonPointPile.STATUS_WAIT) {
								mGunB.setCompoundDrawablesWithIntrinsicBounds(null, null, null,
										ContextCompat.getDrawable(ActivityDoubleGun.this, R.drawable.ico_charging_gun_connected));
								mTip.setVisibility(View.VISIBLE);
								mTip.setText(spanBTip);
								mConnect.setVisibility(View.GONE);
								mLinearTip.setVisibility(View.GONE);
								mNext.setBackgroundResource(R.drawable.bg_main_button_lg_sprite_2);
								mNext.setClickable(true);
								mGunNum = JsonPointPile.GUN_B;
								isChoose = false;
							}

							if (result.gunA == JsonPointPile.STATUS_IDLE) {
								mGunA.setCompoundDrawablesWithIntrinsicBounds(null, null, null,
										ContextCompat.getDrawable(ActivityDoubleGun.this, R.drawable.ico_charging_gun_disconnect));
								isGunAOccupy = false;

							} else if (result.gunA == JsonPointPile.STATUS_WAIT) {
								mGunA.setCompoundDrawablesWithIntrinsicBounds(null, null, null,
										ContextCompat.getDrawable(ActivityDoubleGun.this, R.drawable.ico_charging_gun_connected));
								isGunAOccupy = false;

							} else {
								mGunA.setCompoundDrawablesWithIntrinsicBounds(null, null, null,
										ContextCompat.getDrawable(ActivityDoubleGun.this, R.drawable.ico_charging_gun_disabled));
							}
							//双枪都被占用，理论上不应该执行这一步，这里是以防万一做特殊的处理
						} else {
							mTip.setVisibility(View.VISIBLE);
							mTip.setText(mTextTip);
							mConnect.setVisibility(View.VISIBLE);
							mLinearTip.setVisibility(View.GONE);
							mCheckA.setVisibility(View.GONE);
							mCheckB.setVisibility(View.GONE);
							mRelateGunA.setClickable(false);
							mRelateGunB.setClickable(false);
							mNext.setBackgroundResource(R.drawable.bg_main_button_sm_black);
							mNext.setClickable(false);
							isChoose = false;

							if (result.gunA == JsonPointPile.STATUS_IDLE) {
								mGunA.setCompoundDrawablesWithIntrinsicBounds(null, null, null,
										ContextCompat.getDrawable(ActivityDoubleGun.this, R.drawable.ico_charging_gun_disconnect));
								isGunAOccupy = false;

							} else if (result.gunA == JsonPointPile.STATUS_WAIT) {
								mGunA.setCompoundDrawablesWithIntrinsicBounds(null, null, null,
										ContextCompat.getDrawable(ActivityDoubleGun.this, R.drawable.ico_charging_gun_connected));
								isGunAOccupy = false;

							} else {
								mGunA.setCompoundDrawablesWithIntrinsicBounds(null, null, null,
										ContextCompat.getDrawable(ActivityDoubleGun.this, R.drawable.ico_charging_gun_disabled));
							}

							if (result.gunB == JsonPointPile.STATUS_IDLE) {
								mGunB.setCompoundDrawablesWithIntrinsicBounds(null, null, null,
										ContextCompat.getDrawable(ActivityDoubleGun.this, R.drawable.ico_charging_gun_disconnect));
								isGunBOccupy = false;

							} else if (result.gunB == JsonPointPile.STATUS_WAIT) {
								mGunB.setCompoundDrawablesWithIntrinsicBounds(null, null, null,
										ContextCompat.getDrawable(ActivityDoubleGun.this, R.drawable.ico_charging_gun_connected));
								isGunBOccupy = false;

							} else {
								mGunB.setCompoundDrawablesWithIntrinsicBounds(null, null, null,
										ContextCompat.getDrawable(ActivityDoubleGun.this, R.drawable.ico_charging_gun_disabled));
							}
						}
						handler.postDelayed(runnable, DOUBLE_GUN_REFRESH);

					} else if (result.status == GlobalResult.TOKEN_INVALID.getStatus()) {
						handler.removeCallbacks(runnable);//停止请求枪刷新
						AppContext.getInstance().clearLoginState();
						jumpToLogin(ActivityDoubleGun.this, true);

					} else {
						Toast.makeText(ActivityDoubleGun.this, result.message, Toast.LENGTH_SHORT).show();
						handler.postDelayed(runnable, DOUBLE_GUN_REFRESH);
					}
				}

				@Override
				public void onEErrorResponse(VolleyError error) {
					handler.postDelayed(runnable, DOUBLE_GUN_REFRESH);
					Toast.makeText(ActivityDoubleGun.this, R.string.common_tip_resultfail, Toast.LENGTH_SHORT).show();
				}

				@Override
				public void onEFinish() {
					super.onEFinish();
				}
			});


		}
	};

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		dialogTip();
		return super.onKeyDown(keyCode, event);
	}


	private void dialogTip() {
		new AlertDialog.Builder(ActivityDoubleGun.this)
				.setTitle(R.string.common_dialog_tip)
				.setMessage("是否确定退出当前的操作？")
				.setCancelable(false)
				.setPositiveButton(R.string.common_ok, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {

						finish();
					}
				})
				.setNegativeButton(R.string.common_cancel, null)
				.create().show();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.toolbar_back:
				dialogTip();
				break;
			case R.id.activity_connect:
				Intent intent = new Intent(ActivityDoubleGun.this, ActivityHelp.class);
				startActivity(intent);
				break;
			case R.id.textview_next:
				goToCharging();
				break;
			case R.id.layout_gunA:
				mCheckA.setImageDrawable(ContextCompat.getDrawable(ActivityDoubleGun.this, R.drawable.btn_checkbox_active));
				mCheckB.setImageDrawable(ContextCompat.getDrawable(ActivityDoubleGun.this, R.drawable.btn_checkbox_normal));
				mGunNum = JsonPointPile.GUN_A;
				isChoose = true;
				mNext.setBackgroundResource(R.drawable.bg_main_button_lg_sprite_2);
				mNext.setClickable(true);
				break;
			case R.id.layout_gunB:
				mCheckB.setImageDrawable(ContextCompat.getDrawable(ActivityDoubleGun.this, R.drawable.btn_checkbox_active));
				mCheckA.setImageDrawable(ContextCompat.getDrawable(ActivityDoubleGun.this, R.drawable.btn_checkbox_normal));
				mGunNum = JsonPointPile.GUN_B;
				isChoose = true;
				mNext.setBackgroundResource(R.drawable.bg_main_button_lg_sprite_2);
				mNext.setClickable(true);
				break;
			default:
				break;
		}
	}

	private void goToCharging() {
		handler.removeCallbacks(runnable);

		//判断交直流
		if (mQrScanData == null) {
			Toast.makeText(this, "参数错误，请返回重新连接！", Toast.LENGTH_SHORT).show();
			return;
		}
		if (mQrScanData.isDcCharging()) {
			//直流
			Intent intent = new Intent(this, ActivityChargingDc.class);
			intent.putExtra("gunNum", mGunNum);
			intent.putExtra(JsonQrScan.KEY, mQrScanData);
			intent.putExtra(ActivityChargingDc.KEY_CHARGE_ACTION, ActivityChargingDc.CHARGE_ACTION_WAIT);
			startActivity(intent);
			finish();
		} else if (mQrScanData.isAcCharging()) {
			//交流
			Intent intent = new Intent(this, ActivityChargingAc.class);
			intent.putExtra("gunNum", mGunNum);
			intent.putExtra(JsonQrScan.KEY, mQrScanData);
			intent.putExtra(ActivityChargingAc.KEY_CHARGE_ACTION, ActivityChargingAc.CHARGE_ACTION_WAIT);
			startActivity(intent);
			finish();
		} else {
			Toast.makeText(this, "无法判断充电桩类型！", Toast.LENGTH_SHORT).show();
		}
	}

}
